package cn.explink.eap.web.cgform.controller.autolist;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.explink.eap.core.common.controller.BaseController;
import cn.explink.eap.core.common.model.json.AjaxJson;
import cn.explink.eap.core.common.model.json.DataGrid;
import cn.explink.eap.core.constant.Globals;
import cn.explink.eap.core.util.ResourceUtil;
import cn.explink.eap.core.util.StringUtil;
import cn.explink.eap.web.cgform.common.CgAutoListConstant;
import cn.explink.eap.web.cgform.common.SysVar;
import cn.explink.eap.web.cgform.engine.FreemarkerHelper;
import cn.explink.eap.web.cgform.entity.button.CgformButtonEntity;
import cn.explink.eap.web.cgform.entity.config.CgFormFieldEntity;
import cn.explink.eap.web.cgform.service.autolist.CgTableServiceI;
import cn.explink.eap.web.cgform.service.autolist.ConfigServiceI;
import cn.explink.eap.web.cgform.service.config.CgFormFieldServiceI;
import cn.explink.eap.web.cgform.util.QueryParamUtil;
import cn.explink.eap.web.system.service.SystemService;

/**
 * 
 * @Title:CgAutoListController
 * @description:动态列表控制器[根据表名读取配置文件，进行动态数据展现]
 * @author 赵俊夫
 * @date Jul 5, 2013 2:55:36 PM
 * @version V1.0
 */
@Controller
@RequestMapping("/cgAutoListController")
public class CgAutoListController extends BaseController{
	@Autowired
	private ConfigServiceI configService;
	@Autowired
	private CgTableServiceI cgTableService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private CgFormFieldServiceI cgFormFieldService;
	private static Logger log = Logger.getLogger(CgAutoListController.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 模板生成之前
	 * @param paras 参数map
	 */
	public void beforeList(Map<String, Object> paras) {}
	
	/**
	 * 动态列表展现入口
	 * @param id 动态配置ID
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "list")
	public void list(String id, HttpServletRequest request,
			HttpServletResponse response) {
		long start = System.currentTimeMillis();
		//step.1 根据表名获取该表单的配置参数
		String jversion = cgFormFieldService.getCgFormVersionByTableName(id);
		Map<String, Object> configs = configService.queryConfigs(id,jversion);
		//step.2 获取列表ftl模板路径
		FreemarkerHelper viewEngine = new FreemarkerHelper();
		Map<String, Object> paras = new HashMap<String, Object>();
		//step.3 封装页面数据
		loadVars(configs,paras,request);
		createQueryTable(paras); //排序表格坐标
		createTableRows(paras); //获取行对象
		String extendFtl = (String) configs.get(CgAutoListConstant.EXTEND_FTL_MODEL);
		String html = null;
		beforeList(paras);
		if (org.apache.commons.lang3.StringUtils.isBlank(extendFtl)) {
			//step.4 组合模板+数据参数，进行页面展现
			html = viewEngine.parseTemplate("eap/sys/ftl/eap-autolist.ftl", paras);
		} else {
			html = viewEngine.parseTemplate(extendFtl, paras);
			html += "<script type='text/javascript'>function getUrl(){return 'cgAutoListController.do?loadContainer&configId=" + id
				 + "';}</script><script type='text/javascript' src='eap/sys/js/eapContainer-v2.0.js'></script>";
			 //防止比组件执行得早
			 List<String>  listJs = (List<String>) paras.get("listJs");
			 for (String s : listJs) {
				 html += s; 
			 }
		}
		try {
			response.setContentType("text/html");
			response.setHeader("Cache-Control", "no-store");
			PrintWriter writer = response.getWriter();
			writer.println(html);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		log.debug("动态列表生成耗时："+(end-start)+" ms");
	}

	/**
	 * 动态列表数据查询
	 * @param configId 配置id 修正使用id会造成主键查询的冲突
	 * @param page 分页页面
	 * @param rows 分页大小
	 * @param request 
	 * @param response
	 * @param dataGrid
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "datagrid")
	public void datagrid(String configId,String page,String field,String rows,String sort,String order, HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		long start = System.currentTimeMillis();
		//step.1 获取动态配置
		String jversion = cgFormFieldService.getCgFormVersionByTableName(configId);
		Map<String, Object>  configs = configService.queryConfigs(configId,jversion);
		String table = (String) configs.get(CgAutoListConstant.TABLENAME);
		Map params =  new HashMap<String,Object>();
		//step.2 获取查询条件以及值
		List<CgFormFieldEntity> beans = (List<CgFormFieldEntity>) configs.get(CgAutoListConstant.FILEDS);
		for(CgFormFieldEntity b:beans){
//			if(CgAutoListConstant.BOOL_TRUE.equals(b.getIsQuery())){
				QueryParamUtil.loadQueryParams(request,b,params);
//			}
		}
		int p = page==null?1:Integer.parseInt(page);
		int r = rows==null?99999:Integer.parseInt(rows);
		//step.3 进行查询返回结果
		List<Map<String, Object>> result=cgTableService.querySingle(table, field.toString(), params,sort,order, p,r );
		Long size = cgTableService.getQuerySingleSize(table, field, params);
		dealDic(result,beans);
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-store");
		PrintWriter writer;
		try {
			writer = response.getWriter();
			writer.println(QueryParamUtil.getJson(result,size));
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		log.debug("动态列表查询耗时："+(end-start)+" ms");
	}
	
	/**
	 * 获取元数据信息
	 * @param configId formId
	 * @param request 请求
	 * @return 元数据信息
	 */
	@RequestMapping(params = "loadContainer")
	@ResponseBody
	public AjaxJson loadContainer(String configId, HttpServletRequest request) {
		String jversion = cgFormFieldService.getCgFormVersionByTableName(configId);
		Map<String, Object>  configs = configService.queryConfigs(configId,jversion);
		AjaxJson j = new AjaxJson();
		j.setMsg("OK");
		j.setObj(getContainerDef(configs));
		return j;
	}
	
	/**
	 * 获取区域定义定义信息
	 * @param configs 定义信息
	 * @return 分区域定义信息
	 */
	private Map<String, List<Map<String, Object>>> getContainerDef(Map<String, Object> configs) {
		//button
		List<CgformButtonEntity> buttonList = (List<CgformButtonEntity>) configs.get(CgAutoListConstant.CONFIG_BUTTONLIST);
		//字段
		List<CgFormFieldEntity> fieldList = (List<CgFormFieldEntity>) configs.get(CgAutoListConstant.FILEDS);
		StringBuffer containerStr = new StringBuffer("");
		Set<String> containerSet = new TreeSet<String>();
		for (CgFormFieldEntity field : fieldList) {
			filterDictData(field);
			containerStr.append(field.getAreaIds()).append(",");
		}
		for (CgformButtonEntity button : buttonList) {
			containerStr.append(button.getContainerId()).append(",");
		}
		String[] containerArray = containerStr.toString().split(",");
		//get all container
		for(String s : containerArray) {
			if (org.apache.commons.lang3.StringUtils.isNotBlank(s)) {
				containerSet.add(s);
			}
		}
		Map<String, List<Map<String, Object>>> containerDataList = new TreeMap<String, List<Map<String, Object>>>();
		//分区
		for (String set : containerSet) {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			for (CgFormFieldEntity field : fieldList) {
				Map<String, Object> map = new TreeMap<String, Object>();
				if (field.getAreaIds().contains(set)) {
					map.put("containerId", field.getAreaIds());
					map.put("name", field.getContent());
					map.put("dictCode", field.getDictField());
					map.put("dictText", field.getDictText());
					map.put("id", field.getFieldName());
					map.put("code", field.getFieldName());
					map.put("height", field.getItemHeight());
					map.put("width", field.getItemWidth());
					map.put("listShow", field.getIsShowList());
					map.put("formShow", field.getIsShow());
					map.put("tableCoordinate", field.getTableCoordinate());
					map.put("type", field.getShowType().toLowerCase());
					map.put("sequence", field.getSequence());
					List<Map<String, Object>> dictData = filterDictData(field);
					if (null != dictData && dictData.size() > 0) {
						map.put("dictData", dictData);
					}
					list.add(map);
				}
			}
			for (CgformButtonEntity button : buttonList) {
				Map<String, Object> map = new TreeMap<String, Object>();
				if (button.getContainerId().contains(set)) {
					if (button.getButtonStatus().equals("1")) {
						map.put("type", "button");
						map.put("code", button.getButtonCode());
						map.put("icon", button.getButtonIcon());
						map.put("name", button.getButtonName());
						map.put("containerId", button.getContainerId());
						map.put("formId", button.getFormId());
						map.put("id", button.getId());
						map.put("optType", button.getOptType());
						map.put("exp", button.getExp());
						map.put("sequence", button.getSequence());
						list.add(map);
					}
				}
			}
			containerDataList.put(set, list);
		}
		return sequenceList(containerDataList);
	}

	/**
	 * 排序区域字段
	 * @param containerDataList 分区好的字段信息
	 * @return 排序之后的字段信息
	 */
	private Map<String, List<Map<String, Object>>> sequenceList(Map<String, List<Map<String, Object>>> containerDataList) {
		Map<String, List<Map<String, Object>>> sequenceList = new TreeMap<String, List<Map<String, Object>>>();
		for (String s : containerDataList.keySet()) {
			List<Map<String, Object>> list = containerDataList.get(s);
			List<TreeMap<String, String>> sequList = new ArrayList<TreeMap<String, String>>();
			List<Map<String, Object>> lateSequList = new ArrayList<Map<String, Object>>();
			for (Map<String, Object> m : list) {
				String containerStr = (String) m.get("containerId");
				String[] containerArray = containerStr.split(",");
				for (int i = 0; i < containerArray.length; i++) {
					String thisStr = containerArray[i];
					if (thisStr.equals(s)) {
						TreeMap<String, String> thisMap= new TreeMap<String, String>();
						thisMap.put("code", (String)m.get("code"));
						thisMap.put("index", getsequIndex((String)m.get("sequence"), i));
						sequList.add(thisMap);
					}
				}
			}
			insertionSort(sequList);
			for (TreeMap<String, String> map : sequList) {
				String code = map.get("code");
				for (Map<String, Object> l : list) {
					if (code.equals((String)l.get("code"))) {
						lateSequList.add(l);
					}
				}
			}
			sequenceList.put(s, lateSequList);
		}
		return sequenceList;
	}
	
	/**
	 * 插入排序
	 * @param sequList 排序之前列表
	 */
	private void insertionSort(List<TreeMap<String, String>> sequList) {
	   int length = sequList.size();
 	   for (int i = 1; i < length; i++) {
 	   	  for (int j = 0; j < length - i; j++) {
 	   		  int listIndex = Integer.parseInt(sequList.get(j).get("index"));
 	   		  int listNextIndex = Integer.parseInt(sequList.get(j + 1).get("index"));
 	   		  if (Integer.valueOf(listIndex) > Integer.valueOf(listNextIndex)) {
 	   			  TreeMap<String, String> temp = sequList.get(j);
 	   			  sequList.set(j, sequList.get(j + 1));
 	   			  sequList.set(j + 1, temp);
 	   		  }
 	   	  }
 	   }
	}
	
	/**
	 * 过获取字段排序所在索引
	 * @param sequStr 字段排序字符串
	 * @param index 区域所在索引
	 * @return 字段区域内排序
	 */
	private String getsequIndex(String sequStr, int index) {
		int returnNum = 10000;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(sequStr)) { //不为空
			String[] sequArray = sequStr.split(",");
			for (int i = 0; i < sequArray.length; i++) {
				if (i == Integer.valueOf(index)) {
					returnNum = Integer.parseInt(sequArray[i]);
				}
			}
		}
		return returnNum + "";
	}
	
	/**
	 * 获取字典数据
	 * @param bean 字段配置
	 * @return 字典数据
	 */
	private List<Map<String, Object>> filterDictData(CgFormFieldEntity bean) {
		String dicT = bean.getDictTable();//字典表
		String dicF = bean.getDictField();//字典字段
		String dicText= bean.getDictText();//字典文本
		if(!StringUtil.isEmpty(dicF)){
			if(!bean.getShowType().equals("popup")){
				List<Map<String, Object>> dicDatas = queryDic(dicT, dicF,dicText);
				return dicDatas;
			}
		}
		return null;
	}
	
	/**
	 * 处理数据字典
	 * @param result 查询的结果集
	 * @param beans 字段配置
	 */
	@SuppressWarnings("unchecked")
	private void dealDic(List<Map<String, Object>> result,
			List<CgFormFieldEntity> beans) {
		for(CgFormFieldEntity bean:beans){
			String dicT = bean.getDictTable();//字典表
			String dicF = bean.getDictField();//字典字段
			String dicText= bean.getDictText();//字典文本
			if(StringUtil.isEmpty(dicT)&& StringUtil.isEmpty(dicF)){
				//不需要处理字典
				continue;
			}else{
				if(!bean.getShowType().equals("popup")){
					List<Map<String, Object>> dicDatas = queryDic(dicT, dicF,dicText);
					for(Map r:result){
						String value = String.valueOf(r.get(bean.getFieldName()));
						for(Map m:dicDatas){
							String typecode = String.valueOf(m.get("typecode"));
							String typename = String.valueOf(m.get("typename"));
							if(value.equalsIgnoreCase(typecode)){
								r.put(bean.getFieldName(),typename);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 删除动态表
	 * @param configId 配置id
	 * @param id 主键
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(String configId,String id,
			HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String jversion = cgFormFieldService.getCgFormVersionByTableName(configId);
		String table = (String) configService.queryConfigs(configId,jversion).get(CgAutoListConstant.TABLENAME);
		cgTableService.delete(table, id);
		String message = "删除成功";
		systemService.addLog(message, Globals.Log_Type_DEL,
				Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}
	/**
	 * 删除动态表-批量
	 * @param configId 配置id
	 * @param id 主键
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "delBatch")
	@ResponseBody
	public AjaxJson delBatch(String configId,String ids,
			HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String jversion = cgFormFieldService.getCgFormVersionByTableName(configId);
		String table = (String) configService.queryConfigs(configId,jversion).get(CgAutoListConstant.TABLENAME);
		String message = "删除成功";
		try {
			String[] id = ids.split(",");
			cgTableService.deleteBatch(table, id);
		} catch (Exception e) {
			message = e.getMessage();
		}
		systemService.addLog(message, Globals.Log_Type_DEL,
				Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}
	
	
	/**
	 * 根据表字段逆向生成表单
	 * @param tableName 表名
	 * @param isExitItems 当前存在字段
	 * @param request 请求
	 * @author hedy
	 * @return 表字段属性
	 */
	@RequestMapping(params = "syncDbTable")
	@ResponseBody
	public AjaxJson syncDbTable(String tableName, String isExitItems, HttpServletRequest request) {
		List<Map<String, String>> colunmList = new ArrayList<Map<String, String>>(); //字段定义
		AjaxJson j = new AjaxJson();
		String message = "";
		DataSource dataSource = jdbcTemplate.getDataSource();
		Connection conn = null;
		String[] isExitItemArray = null;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(isExitItems)) { //不为空
			isExitItemArray = isExitItems.split(","); //已存在的字段
		}
		try {
			conn = dataSource.getConnection();
			DatabaseMetaData dbmd = conn.getMetaData();
			ResultSet resultSet = dbmd.getTables(null, "%", "%", new String[] { "TABLE" });
			while (resultSet.next()) {
                String thisTableName = resultSet.getString("TABLE_NAME");
                if(tableName.equals(thisTableName)){
                    ResultSet columnDef = dbmd.getColumns(null, "%", tableName, "%");
                    while(columnDef.next()){
                    	Map<String, String> map = new HashMap<String, String>();
                    	String columnName = columnDef.getString("COLUMN_NAME");
                    	boolean isExite = false; //是否存在标示
                    	for (String s  : isExitItemArray) {
                    		if (s.equals(columnName)) {
                    			isExite = true;
                    		}
                    	}
                    	if (!isExite) { //不存在则回显
        					map.put("name", columnDef.getString("COLUMN_NAME"));
        					map.put("size", columnDef.getString("COLUMN_SIZE"));
        					map.put("type", formatColumnType(columnDef.getString("TYPE_NAME")));
        					map.put("scale", columnDef.getString("DECIMAL_DIGITS"));
        					map.put("isNull", columnDef.getInt("NULLABLE") > 0 ? "N" : "Y");
        					map.put("content", columnDef.getString("REMARKS"));
        					map.put("fieldDefault", columnDef.getString("COLUMN_DEF"));
        					map.put("isKey", "N");
        					//获取主键字段
                            ResultSet pkDef = dbmd.getPrimaryKeys(null, null, tableName);
                            while(pkDef.next()) {
                            	if (columnName.equals(pkDef.getString("COLUMN_NAME"))) { //同一字段
                            		map.put("isKey", "Y");
                            		map.put("fieldDefault", "");
                            		break;
                            	}
                            }
                            colunmList.add(map);
                    	}
                    }
                    break;
                }
            }
			message = "同步成功！";
		} catch (SQLException e) {
			message = "同步失败！";
			systemService.addLog(e.getMessage(), Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		systemService.addLog(message, Globals.Log_Type_DEL,
				Globals.Log_Leavel_INFO);
		j.setObj(colunmList);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 获取页面所需字段数据类型
	 * @param columnType db字段类型
	 * @author hedy
	 * @return 页面所需字段数据类型
	 */
	private String formatColumnType(String columnType) {
		String columnTypeUpperCase = columnType.toUpperCase();
		if (columnTypeUpperCase.equals("VARCHAR")) { //字符型
			return "string";
		} else if (columnTypeUpperCase.equals("INTEGER") || columnTypeUpperCase.equals("INT")) {
			return "int";
		} else if (columnTypeUpperCase.equals("NUMERIC") || columnTypeUpperCase.equals("DOUBLE") || columnTypeUpperCase.equals("FLOAT")) {
			return "double";
		} else if (columnTypeUpperCase.equals("DATE") || columnTypeUpperCase.equals("DATETIME")) {
			return "Date";
		} else if (columnTypeUpperCase.equals("DECIMAL")) {
			return "BigDecimal";
		}
		return columnType;
	}
	
	/**
	 * 创建表格行对象列表
	 * @param paras 参数
	 */
	private void createTableRows(Map<String, Object> paras) {
		//获取表格坐标排序之后的列表
		List<Map<String, Object>> list = (List<Map<String, Object>>) paras.get("sortQueryList");
		List<List<String>> trList = new ArrayList<List<String>>(); //行对象列表
		Set<Integer> rowIndexSet = new TreeSet<Integer>();
		//获取行数
		for (Map<String, Object> map : list) {
			String[] tempArray = (String[])map.get(CgAutoListConstant.TABLECOORDINATE_SORT);
			int rowNum = Integer.parseInt(tempArray[0]);
			rowIndexSet.add(rowNum);
		}
		for (int i : rowIndexSet) { //添加行数据
			List<String> tdList = new ArrayList<String>();
			for (Map<String, Object> map : list) {
				//获取表格排序数组
				String[] tempArray = (String[])map.get(CgAutoListConstant.TABLECOORDINATE_SORT);
				int rowNum = Integer.parseInt(tempArray[0]); //行索引
				StringBuffer td = new StringBuffer();
				if (i == rowNum) { //同一行
					td.append("<td rowspan='").append(Integer.parseInt(tempArray[2])).append("'").append(" ");
					td.append("colspan='").append(Integer.parseInt(tempArray[3])).append("'").append(" ");
					td.append("code='").append(map.get(CgAutoListConstant.FILED_ID)).append("'").append(" ");
					td.append("style='vertical-align: middle'");
					td.append(">");
					td.append("</td>");
				}
				tdList.add(td.toString());
			}
			trList.add(tdList);
		}
		paras.put("trList", trList);
	}
	
	/**
	 * 创建查询区域表格  
	 * @param paras
	 */
	private void createQueryTable(Map<String, Object> paras) {
		//List<String[]> list = new ArrayList<String[]>(); //获取表格坐标数组
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> queryList = (List<Map<String, Object>>) paras.get(CgAutoListConstant.CONFIG_QUERYLIST);
		for (Map<String, Object> map : queryList) {
			String tableCoordinate = (String)map.get(CgAutoListConstant.FIELD_TABLECOORDINATE); //获取表格设置坐标
			if (StringUtils.isNotBlank(tableCoordinate)) { //不为空
				map.put(CgAutoListConstant.TABLECOORDINATE_SORT, tableCoordinate.split(","));
				list.add(map);
			}/*else {
				list.add(tableCoordinate.split(","));
			}*/
		}
		sortList(list, 1);
		sortList(list, 0);
		paras.put("sortQueryList", list);
	}
	
	/**
	 * Insertion Sorting
	 */
	private void sortList(List<Map<String, Object>> list, int sortIndex) {
		int length = list.size();
		for (int i = 1; i < list.size(); i++) {
			for (int j = 0; j < length - i; j++) {
				int listIndex = Integer.parseInt(((String[])((Map<String, Object>)list.get(j)).get(CgAutoListConstant.TABLECOORDINATE_SORT))[sortIndex]);
				int listNextIndex = Integer.parseInt(((String[])((Map<String, Object>)list.get(j + 1)).get(CgAutoListConstant.TABLECOORDINATE_SORT))[sortIndex]);
				if (listIndex > listNextIndex) {
					Map<String, Object> temp = list.get(j);
					list.set(j, list.get(j + 1));
					list.set(j + 1,  temp);
				}
			}
		}
	}
	
	/**
	 * 装载要传入到ftl中的变量
	 * @param configs 从数据库中取出来的配置
	 * @param paras 要传入ftl的参数（需要对configs进行一些改造）
	 * @param request 
	 * @return 要传入ftl的参数（该方法直接操作paras容器，当然可以使用此返回值）
	 */
	@SuppressWarnings("unchecked")
	private Map loadVars(Map<String, Object> configs,Map<String, Object> paras, HttpServletRequest request) {
		paras.putAll(configs);
		List<Map> fieldList = new ArrayList<Map>();
		List<Map> queryList = new ArrayList<Map>();
		StringBuilder fileds = new StringBuilder();
		StringBuilder initQuery = new StringBuilder();
		for (CgFormFieldEntity bean : (List<CgFormFieldEntity>) configs.get(CgAutoListConstant.FILEDS)) {
			Map fm = new HashMap<String, Object>();
			fm.put(CgAutoListConstant.FILED_ID, bean.getFieldName());
			fm.put(CgAutoListConstant.FIELD_TITLE, bean.getContent());
			String isShowList = bean.getIsShowList();
			if(StringUtil.isEmpty(isShowList)){
				if("id".equalsIgnoreCase(bean.getFieldName())){
					isShowList = CgAutoListConstant.BOOL_FALSE;
				}else{
					isShowList = CgAutoListConstant.BOOL_TRUE;
				}
			}
			fm.put(CgAutoListConstant.FIELD_ISSHOW, isShowList);
			fm.put(CgAutoListConstant.FIELD_QUERYMODE, bean.getQueryMode());
			fm.put(CgAutoListConstant.FIELD_SHOWTYPE, bean.getShowType());
			fm.put(CgAutoListConstant.FIELD_TYPE, bean.getType());
			fm.put(CgAutoListConstant.FIELD_LENGTH, bean.getFieldLength()==null?"120":bean.getFieldLength());
			fm.put(CgAutoListConstant.FIELD_HREF, bean.getFieldHref()==null?"":bean.getFieldHref());
			fm.put(CgAutoListConstant.FIELD_TABLECOORDINATE, bean.getTableCoordinate());
			loadDic(fm,bean);
			fieldList.add(fm);
			if (CgAutoListConstant.BOOL_TRUE.equals(bean.getIsQuery())) {
				Map fmq = new HashMap<String, Object>();
				fmq.put(CgAutoListConstant.FILED_ID, bean.getFieldName());
				fmq.put(CgAutoListConstant.FIELD_TITLE, bean.getContent());
				fmq.put(CgAutoListConstant.FIELD_QUERYMODE, bean.getQueryMode());
				fmq.put(CgAutoListConstant.FIELD_TYPE, bean.getType());
				fmq.put(CgAutoListConstant.FIELD_SHOWTYPE, bean.getShowType());
				fmq.put(CgAutoListConstant.FIELD_DICTFIELD, bean.getDictField());
				fmq.put(CgAutoListConstant.FIELD_DICTTABLE, bean.getDictTable());
				fmq.put(CgAutoListConstant.FIELD_ISQUERY,"Y");
				fmq.put(CgAutoListConstant.FIELD_TABLECOORDINATE, bean.getTableCoordinate());
				loadDefaultValue(fmq,bean,request);
				loadDic(fmq,bean);
				queryList.add(fmq);
			}
			loadUrlDataFilter(queryList,bean,request);
			loadInitQuery(initQuery,bean,request);
			fileds.append(bean.getFieldName()).append(",");
		}
		loadAuth(paras, request);
		loadIframeConfig(paras, request);
		paras.put(CgAutoListConstant.CONFIG_FIELDLIST, fieldList);
		paras.put(CgAutoListConstant.CONFIG_QUERYLIST, queryList);
		paras.put(CgAutoListConstant.FILEDS, fileds);
		paras.put(CgAutoListConstant.INITQUERY, initQuery);
		return paras;
	}
	/**
	 * 加载iframe设置
	 * @param paras
	 * @param request
	 */
	private void loadIframeConfig(Map<String, Object> paras,
			HttpServletRequest request) {
		//如果列表以iframe形式的话，需要加入样式文件
		StringBuilder sb= new StringBuilder("");
		if(request.getQueryString().contains("isIframe")){
			sb.append("<script type=\"text/javascript\" src=\"plug-in/jquery/jquery-1.8.3.js\"></script>");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/tools/dataformat.js\"></script>");
			sb.append("<link id=\"easyuiTheme\" rel=\"stylesheet\" href=\"plug-in/easyui/themes/default/easyui.css\" type=\"text/css\"></link>");
			sb.append("<link rel=\"stylesheet\" href=\"plug-in/easyui/themes/icon.css\" type=\"text/css\"></link>");
			sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"plug-in/accordion/css/accordion.css\">");
			sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"plug-in/accordion/css/icons.css\">");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/easyui/jquery.easyui.min.1.3.2.js\"></script>");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/easyui/locale/easyui-lang-zh_CN.js\"></script>");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/tools/syUtil.js\"></script>");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/My97DatePicker/WdatePicker.js\"></script>");
			sb.append("<link rel=\"stylesheet\" href=\"plug-in/tools/css/common.css\" type=\"text/css\"></link>");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/lhgDialog/lhgdialog.min.js\"></script>");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/tools/curdtools.js\"></script>");
			sb.append("<script type=\"text/javascript\" src=\"plug-in/tools/easyuiextend.js\"></script>");
		}else{
		}
		paras.put(CgAutoListConstant.CONFIG_IFRAME, sb.toString());
	}
	/**
	 * 加载按钮权限
	 * @param paras
	 * @param request
	 */
	private void loadAuth(Map<String, Object> paras, HttpServletRequest request) {
		List<String> nolist = (List<String>) request.getAttribute("noauto_operationCodes");
		if(ResourceUtil.getSessionUserName().getUserName().equals("admin")|| !Globals.BUTTON_AUTHORITY_CHECK){
			nolist = null;
		}
		String nolistStr = "";
		if(nolist!=null){
			for(String no:nolist){
				nolistStr+=no;
				nolistStr+=",";
			}
		}
		paras.put(CgAutoListConstant.CONFIG_NOLIST, nolist==null?new ArrayList<String>(0):nolist);
		paras.put(CgAutoListConstant.CONFIG_NOLISTSTR, nolistStr==null?"":nolistStr);
	}
	/**
	 * 加载列表初始查询条件-
	 * @param initQuery
	 * @param bean
	 * @param request
	 */
	private void loadInitQuery(StringBuilder initQuery, CgFormFieldEntity bean,
			HttpServletRequest request) {
		if(bean.getFieldName().equalsIgnoreCase("id")){
			return;
		}
		String paramV = request.getParameter(bean.getFieldName());
		String paramVbegin = request.getParameter(bean.getFieldName()+"_begin");
		String paramVend = request.getParameter(bean.getFieldName()+"_end");
		paramV = SysVar.getSysVar(paramV);
		paramVbegin = SysVar.getSysVar(paramVbegin);
		paramVend = SysVar.getSysVar(paramVend);
		if(!StringUtil.isEmpty(paramV)){
			initQuery.append("&"+bean.getFieldName()+"="+paramV);
		}
		if(!StringUtil.isEmpty(paramVbegin)){
			initQuery.append("&"+bean.getFieldName()+"_begin="+paramVbegin);
		}
		if(!StringUtil.isEmpty(paramVend)){
			initQuery.append("&"+bean.getFieldName()+"_end="+paramVend);
		}
	}

	/**
	 * 加载URL中的过滤参数[在未配置查询字段的情况下，作为hidden控件使用]
	 * @param queryList
	 * @param bean
	 * @param request
	 */
	@SuppressWarnings("unchecked")
	private void loadUrlDataFilter(List<Map> queryList, CgFormFieldEntity bean,
			HttpServletRequest request) {
		String paramV = request.getParameter(bean.getFieldName());
		String paramVbegin = request.getParameter(bean.getFieldName()+"_begin");
		String paramVend = request.getParameter(bean.getFieldName()+"_end");
		if(bean.getFieldName().equalsIgnoreCase("id")){
			return;
		}
		for(Map mq:queryList){
			if(mq.containsValue(bean.getFieldName())){
				return;
			}
		}
		if(!StringUtil.isEmpty(paramV) || !StringUtil.isEmpty(paramVbegin) ||!StringUtil.isEmpty(paramVend)){
			Map fmq = new HashMap<String, Object>();
			fmq.put(CgAutoListConstant.FILED_ID, bean.getFieldName());
			fmq.put(CgAutoListConstant.FIELD_TITLE, bean.getContent());
			fmq.put(CgAutoListConstant.FIELD_QUERYMODE, bean.getQueryMode());
			fmq.put(CgAutoListConstant.FIELD_TYPE, bean.getType());
			fmq.put(CgAutoListConstant.FIELD_ISQUERY,"N");
			paramV = SysVar.getSysVar(paramV);
			fmq.put(CgAutoListConstant.FIELD_VALUE, paramV);
			paramVbegin = SysVar.getSysVar(paramVbegin);
			paramVend = SysVar.getSysVar(paramVend);
			fmq.put(CgAutoListConstant.FIELD_VALUE_BEGIN, StringUtil.isEmpty(paramVbegin)?"":paramVbegin);
			fmq.put(CgAutoListConstant.FIELD_VALUE_END, StringUtil.isEmpty(paramVend)?"":paramVend);
			queryList.add(fmq);
		}
	}

	/**
	 * 加载URL中的过滤参数[在已配置查询字段的情况下，给该查询字段加上默认值]
	 * @param fmq
	 * @param bean
	 * @param request
	 */
	@SuppressWarnings("unchecked")
	private void loadDefaultValue(Map fmq, CgFormFieldEntity bean,
			HttpServletRequest request) {
		if(bean.getQueryMode().equalsIgnoreCase("single")){
			String paramV = request.getParameter(bean.getFieldName());
			if(!StringUtil.isEmpty(paramV)){
				paramV = SysVar.getSysVar(paramV);
				fmq.put(CgAutoListConstant.FIELD_VALUE, paramV);
			}
		}else if(bean.getQueryMode().equalsIgnoreCase("group")){
			String paramVbegin = request.getParameter(bean.getFieldName()+"_begin");
			String paramVend = request.getParameter(bean.getFieldName()+"_end");
			paramVbegin = SysVar.getSysVar(paramVbegin);
			paramVend = SysVar.getSysVar(paramVend);
			fmq.put(CgAutoListConstant.FIELD_VALUE_BEGIN, StringUtil.isEmpty(paramVbegin)?"":paramVbegin);
			fmq.put(CgAutoListConstant.FIELD_VALUE_END, StringUtil.isEmpty(paramVend)?"":paramVend);
		}
	}

	/**
	 * 装载数据字典
	 * @param m	要放入freemarker的数据
	 * @param bean 读取出来的动态配置数据
	 */
	@SuppressWarnings("unchecked")
	private void loadDic(Map m, CgFormFieldEntity bean) {
		String dicT = bean.getDictTable();//字典表
		String dicF = bean.getDictField();//字典字段
		String dicText = bean.getDictText();//字典文本
		if(StringUtil.isEmpty(dicT)&& StringUtil.isEmpty(dicF)){
			//如果这两个字段都为空，则没有数据字典
			m.put(CgAutoListConstant.FIELD_DICTLIST, new ArrayList(0));
			return;
		}
		if(!bean.getShowType().equals("popup")){
			List<Map<String, Object>> dicDatas = queryDic(dicT, dicF,dicText);
			m.put(CgAutoListConstant.FIELD_DICTLIST, dicDatas);
		}else{
			m.put(CgAutoListConstant.FIELD_DICTLIST, new ArrayList(0));
		}
	}
	/**
	 * 查询数据字典
	 * @param dicT 数据字典表
	 * @param dicF	数据字典字段
	 * @param dicText 数据字典显示文本
	 * @return
	 */
	private List<Map<String, Object>> queryDic(String dicT, String dicF,String dicText) {
		StringBuilder dicSql = new StringBuilder();
		if(StringUtil.isEmpty(dicT)){//step.1 如果没有字典表则使用系统字典表
			dicT = CgAutoListConstant.SYS_DIC;
			dicSql.append(" SELECT TYPECODE,TYPENAME FROM");
			dicSql.append(" "+dicT);
			dicSql.append(" "+"WHERE TYPEGROUPID = ");
			dicSql.append(" "+"(SELECT ID FROM "+CgAutoListConstant.SYS_DICGROUP+" WHERE TYPEGROUPCODE = '"+dicF+"' )");
		}else{//step.2 如果给定了字典表则使用该字典表，这个功能需要在表单配置追加字段
			//table表查询
			dicSql.append("SELECT DISTINCT ").append(dicF).append(" as typecode, ");
			if(dicText!=null&&dicText.length()>0){
				dicSql.append(dicText).append(" as typename ");
			}else{
				dicSql.append(dicF).append(" as typename ");
			}
			dicSql.append(" FROM ").append(dicT);
			dicSql.append(" ORDER BY ").append(dicF);
		}
		//step.3 字典数据
		List<Map<String, Object>> dicDatas = systemService.findForJdbc(dicSql.toString());
		return dicDatas;
	}
}
